/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kymjs.contacts.slice;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONObject;
import org.kymjs.contacts.ContactsAdapter;
import org.kymjs.contacts.HanziToPinyin;
import org.kymjs.contacts.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import org.kymjs.contacts.bean.Contact;
import org.kymjs.contacts.widget.SideBar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice implements Text.TextObserver, SideBar.OnTouchingLetterChangedListener {

    private ContactsAdapter contactsAdapter;
    private ListContainer listContainer;
    private List<Contact> datas;
    private Image delete;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        SideBar mSideBar = (SideBar) findComponentById(ResourceTable.Id_school_friend_sidrbar);
        Text mDialog = (Text) findComponentById(ResourceTable.Id_school_friend_dialog);
        TextField mSearchInput = (TextField) findComponentById(ResourceTable.Id_school_friend_member_search_input);
        delete = (Image) findComponentById(ResourceTable.Id_delete);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_school_friend_member);

        mSideBar.setTextView(mDialog);
        mSideBar.setOnTouchingLetterChangedListener(this);
        mSearchInput.addTextObserver(this);

        contactsAdapter = new ContactsAdapter(getContext(), getData(),getData().size());
        listContainer.setItemProvider(contactsAdapter);
        delete.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                mSearchInput.setText("");
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onTextUpdated(String s, int i, int i1, int i2) {
        if (s.length()>0){
            delete.setVisibility(Component.VISIBLE);
        }else {
            delete.setVisibility(Component.HIDE);
        }
        List<Contact> temp = new ArrayList<>();
        for (Contact data : datas) {
            if (data.getName().contains(s) || data.getPinyin().contains(s)) {
                  temp.add(data);
            }
        }
        if (contactsAdapter != null) {
            contactsAdapter.refresh(temp);
        }
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        int position = 0;
        // 该字母首次出现的位置
        if (contactsAdapter != null) {
            position = contactsAdapter.getPositionForSection(s.charAt(0));
        }
        if (position != -1) {
            contactsAdapter.scrollToSection(position,listContainer);
        } else if (s.contains("#")) {
            contactsAdapter.scrollToSection(0,listContainer);
        }
    }

    /**
     * 模拟数据 原库数据接口无法使用 使用城市数据演示
     *
     * @return List<Contact>
     */
    public List<Contact> getData() {
        ohos.global.resource.ResourceManager resManager = getResourceManager();
        ohos.global.resource.RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/china_city.json");
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    rawFileEntry.openRawFile()));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Contact> list = new ArrayList<>();
        Contact test = new Contact();
        test.setName("_test_");
        test.setPinyin(HanziToPinyin.getPinYin(test.getName()));
        list.add(test);
        ZSONArray array = ZSONArray.stringToZSONArray(stringBuilder.toString());
        for (int i = 0; i < array.size(); i++) {
            ZSONObject object = array.getZSONObject(i);
            Contact data = new Contact();
            data.setName(object.getString("name"));
//            data.setUrl(object.getString("portrait"));
//            data.setId(object.getIntValue("id"));
//            data.setPinyin(HanziToPinyin.getPinYin(data.getName()));
            data.setPinyin(object.getString("pinyin"));
            list.add(data);
        }
        datas=list;
        return list;
    }
}
